package com.hd.crdao.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.GetStoreInfoBean;
import com.hd.crdao.bean.MessageEvent;
import com.hd.crdao.bean.MsgBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.StringUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.GlideImageUtils;
import com.hss01248.dialog.StyledDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/7/25 0025
 */

public class ChangeShopInfoActivity extends BaseSecondActivity implements View.OnClickListener {

    private static final int FROM_CAMERA = 103;
    private static final int FROM_PIC = 104;


    public int count;
    public ArrayList<String> imagePaths = new ArrayList<>();
    @BindView(R.id.createshop_head)
    ExpandHeadView mCreateshopHead;
    @BindView(R.id.shop_icon)
    ImageView mShopIcon;
    @BindView(R.id.shop_name)
    EditText mShopName;
    @BindView(R.id.shop_address)
    TextView mShopAddress;
    @BindView(R.id.inputaddress)
    LinearLayout mInputAddress;
    @BindView(R.id.shop_telephone)
    EditText mShopTelephone;
    @BindView(R.id.openshoptime)
    TextView mOpenshoptime;
    @BindView(R.id.closeshoptime)
    TextView mCloseshoptime;
    @BindView(R.id.shop_introduction)
    EditText mShopIntroduction;
    @BindView(R.id.shop_indeximage)
    ImageView mShopIndeximage;
    @BindView(R.id.btnSubmit_createshop)
    Button mBtnSubmitCreateshop;
    public String areaId;
    public String shopId;
    public String storeLatlon;
    public Handler mHandler = new Handler();
    public String allAddress;

    @Override
    protected int setContentView() {
        return R.layout.activity_changeshopinfo;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mCreateshopHead;
    }

    @Override
    protected void initView() {
        initData();
        initEvent();
        EventBus.getDefault().register(this);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        StyledDialog.buildMdLoading().setActivity(this).show();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.post().url(Constants.GETSTOREINFO_URL)
                        .addParams("sign", Constants.SIGN)
                        .addParams("carBusinessId", SPUtils.getString("businessid", ""))
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show("网络开了个小差");
                        StyledDialog.dismissLoading();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ALog.d(response);
                        GetStoreInfoBean getStoreInfoBean = new Gson().fromJson(response, GetStoreInfoBean.class);
                        if (getStoreInfoBean.getSuccess() == 0) {
                            setSomeParams(getStoreInfoBean);
                            StyledDialog.dismissLoading();
                        }
                    }
                });
            }
        }, 2000);

    }

    /**
     * 当进入店铺设置的时候,需要手动加载一些参数进去
     *
     * @param getStoreInfoBean
     */
    private void setSomeParams(GetStoreInfoBean getStoreInfoBean) {
        GetStoreInfoBean.StoreInfoBean storeInfo = getStoreInfoBean.getStoreInfo();
        if (TextUtils.isEmpty(storeInfo.getStoreLogo())) {
            mShopIcon.setImageResource(R.drawable.logo_moren_2x);
        } else {
            GlideImageUtils.loadImage(Constants.IMAGEURL + storeInfo.getStoreLogo(),R.drawable.logo_moren_2x,true,mShopIcon);
          /*  Glide.with(UIUtils.getContext()).load()
                    .bitmapTransform(new GlideCircleTransform(UIUtils.getContext()))
                    .skipMemoryCache(true).placeholder(R.drawable.logo_moren_2x).into(mShopIcon);*/
        }
        mShopName.setText(storeInfo.getStoreName());
        mShopAddress.setText(storeInfo.getStoreAddress());
        allAddress = storeInfo.getStoreAddress();
        mShopTelephone.setText(storeInfo.getStoreMobile());
        String hours = storeInfo.getBusinessHours();
        String[] businessHours = hours.contains(",") ? hours.split(",") : hours.split("-");
        mOpenshoptime.setText(businessHours[0]);
        mCloseshoptime.setText(businessHours[1]);
        mShopIntroduction.setText(storeInfo.getStoreProfile());
        if (TextUtils.isEmpty(storeInfo.getStoreImage())) {
            mShopIndeximage.setImageResource(R.drawable.icon);
        } else {
            GlideImageUtils.loadImage(Constants.IMAGEURL + storeInfo.getStoreImage(),R.drawable.icon,mShopIndeximage);
          /*  Glide.with(UIUtils.getContext()).load()
                    .skipMemoryCache(true)
                    .bitmapTransform(new GlideCircleTransform(UIUtils.getContext())).placeholder().into(mShopIndeximage);*/
        }
        ALog.d(storeInfo.getCodeImage());
        areaId = storeInfo.getArea().getId();
        shopId = storeInfo.getId();
        storeLatlon = storeInfo.getStoreLatlon();


    }

    /**
     * 初始化
     */
    private void initEvent() {
        imagePaths.add(0, "");
        imagePaths.add(1, "");
        mShopIcon.setOnClickListener(this);
        mShopIndeximage.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shop_icon:
                count = 0;
                upLoadIdcardImage();
                break;
            case R.id.shop_indeximage:
                count = 1;
                upLoadIdcardImage();
                break;
        }
    }

    /**
     * 上传证件照片
     */
    private void upLoadIdcardImage() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.camera_pop_menu, null);
        Button btnCamera = (Button) popView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) popView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) popView.findViewById(R.id.btn_camera_pop_cancel);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开系统照相机
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, FROM_CAMERA);
                popWindow.dismiss();
            }
        });
        btnAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从系统相册中获取照片
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, FROM_PIC);
                popWindow.dismiss();
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
    }


    /**
     * 返回结果中拿到图片路径并赋值
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == FROM_CAMERA && resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                File file = new File(Environment.getExternalStorageDirectory() + "/myImage/");
                file.mkdirs();
                String fileName = Environment.getExternalStorageDirectory() + "/myImage/" + System.currentTimeMillis() + ".jpg";
                try {
                    FileOutputStream fos = new FileOutputStream(fileName);
                    assert bitmap != null;
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                    fos.flush();
                    fos.close();
                    ALog.d("照片已保存到：" + fileName);
                    if (count == 0) {
                       // Glide.with(UIUtils.getContext()).load(fileName).placeholder(R.drawable.logo_moren_2x).into(mShopIcon);
                        GlideImageUtils.loadImage(fileName,R.drawable.logo_moren_2x,mShopIcon);
                    } else if (count == 1) {
                        GlideImageUtils.loadImage(fileName,R.drawable.logo_moren_2x,mShopIndeximage);
                      //  Glide.with(UIUtils.getContext()).load(fileName).placeholder(R.drawable.logo_moren_2x).into(mShopIndeximage);
                    }
                    imagePaths.set(count, fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //从图库选择返回的结果
        if (requestCode == FROM_PIC && resultCode == RESULT_OK) {

            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String imagePath = cursor.getString(columnIndex);
                if (count == 0) {
                  //  Glide.with(UIUtils.getContext()).load(imagePath).placeholder(R.drawable.logo_moren_2x).into(mShopIcon);
                    GlideImageUtils.loadImage(imagePath,R.drawable.logo_moren_2x,mShopIcon);
                } else if (count == 1) {
                  //  Glide.with(UIUtils.getContext()).load(imagePath).placeholder(R.drawable.logo_moren_2x).into(mShopIndeximage);
                    GlideImageUtils.loadImage(imagePath,R.drawable.logo_moren_2x,mShopIndeximage);
                }

                ALog.d(imagePath);
                imagePaths.set(count, imagePath);
                cursor.close();
            }
        }

        //  super.onActivityResult(requestCode, resultCode, data);
    }


    @OnClick({R.id.openshoptime, R.id.closeshoptime, R.id.btnSubmit_createshop, R.id.inputaddress})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.inputaddress:
                ALog.d("选择地址");
                Intent intent = new Intent(UIUtils.getContext(), ChangeAddressActivity.class);
                intent.putExtra("selectlevel", Config.SELECTAREA);
                ALog.d(allAddress);
                String parseAddress = StringUtils.ParseAddress(allAddress);
                if (TextUtils.isEmpty(parseAddress.replace(",", ""))) {
                    String storeAddress = mShopAddress.getText().toString().trim();
                    intent.putExtra("allAddress", StringUtils.ParseAddress(storeAddress));
                } else {
                    intent.putExtra("allAddress", parseAddress);
                }
                startActivity(intent);
                break;
            case R.id.openshoptime:
                timeSelected("开店时间", mOpenshoptime);
                break;
            case R.id.closeshoptime:
                timeSelected("闭店时间", mCloseshoptime);
                break;
            case R.id.btnSubmit_createshop:
                StyledDialog.buildLoading().setActivity(this).show();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        changeSomeInfo();
                    }
                }, 1500);

                break;
        }
    }

    private void changeSomeInfo() {
        String shopName = mShopName.getText().toString().trim();
        String storeAddress = mShopAddress.getText().toString().trim();
        String storeMobile = mShopTelephone.getText().toString().trim();
        String opentime = mOpenshoptime.getText().toString().trim();
        String closetime = mCloseshoptime.getText().toString().trim();
        String storeProfile = mShopIntroduction.getText().toString().trim();

        upLoadSomeInformations(shopName, storeAddress, storeMobile, opentime, closetime, storeProfile, areaId, shopId);
    }


    private void upLoadSomeInformations(String shopName, String storeAddress, String storeMobile, String opentime, String closetime, String storeProfile, String areaId, String shopId) {
        String businessid = SPUtils.getString("businessid", "");
        HashMap<String, String> map = new HashMap<>();
        map.put("sign", Constants.SIGN);
        map.put("id", shopId);
        map.put("carBusinessId", businessid);
        map.put("storeName", shopName);
        map.put("storeAddress", storeAddress);
        map.put("storeLatlon", storeLatlon);
        map.put("storeMobile", storeMobile);
        map.put("businessHours", opentime + "," + closetime);
        if (!TextUtils.isEmpty(storeProfile)) {
            map.put("storeProfile", storeProfile);
        }
        map.put("areaId", areaId);
        PostFormBuilder params = OkHttpUtils.post().url(Constants.CREATEANDUPDATESHOP_URL).params(map);
        if (!TextUtils.isEmpty(imagePaths.get(0))) {
            //  map.put("storeLogo", imagePaths.get(0));
            params.addFile("storeLogo", imagePaths.get(0), new File(imagePaths.get(0)));
        }
        if (!TextUtils.isEmpty(imagePaths.get(1))) {
            // map.put("storeImage", imagePaths.get(1));
            params.addFile("storeImage", imagePaths.get(1), new File(imagePaths.get(1)));
        }
        params.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
                StyledDialog.dismissLoading();
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                MsgBean msgBean = new Gson().fromJson(response, MsgBean.class);
                if (msgBean.getSuccess() == 0) {
                    startActivity(new Intent(UIUtils.getContext(), MyShopActivity.class));
                    finish();
                    MyToast.show(msgBean.getMessage());

                } else {
                    MyToast.show(msgBean.getMessage());
                }
                StyledDialog.dismissLoading();
            }
        });
    }


    /**
     * 时间选择器
     *
     * @param title
     * @param textView
     */
    private void timeSelected(String title, final TextView textView) {
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                textView.setText(String.valueOf(new SimpleDateFormat("HH:mm", Locale.CHINESE).format(date)));
            }
        })
                .setType(new boolean[]{false, false, false, true, true, false})//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText(title)//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.parseColor("#2e2e2e"))//标题文字颜色
                .setSubmitColor(Color.parseColor("#2e2e2e"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#2e2e2e"))//取消按钮文字颜色
                .setTitleBgColor(0x000000)//标题背景颜色 Night mode
                .setBgColor(0x000000)//滚轮背景颜色 Night mode
                .setDate(Calendar.getInstance())// 默认是系统时间*/
                .setLabel(null, null, null, "时", "分", null)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getLocation(MessageEvent messageEvent) {
        mShopAddress.setText(messageEvent.getAddress());
        storeLatlon = messageEvent.getLocation();
        ALog.d(messageEvent.getAddress());
        ALog.d(messageEvent.getLocation());
    }
}
